from bs4 import BeautifulSoup
import markdown
from flask import Blueprint, render_template, request, redirect, jsonify, url_for, session, flash, current_app
from sqlalchemy.exc import SQLAlchemyError

from applications.models.frontend import Article, ArtComment, ArticleCate, User
from applications.extensions import db

from applications.view.user.decorators import login_required # 从新的模块导入装饰器
# 创建故事管理蓝图
story_bp = Blueprint('story', __name__)

# 前台故事页面
@story_bp.route('/')
@story_bp.route('/story')
def story():
    user_id = session.get('user_id')
    current_user = User.query.get(user_id) if user_id else None

    # 获取分类信息
    selected_categories = ArticleCate.query.filter(ArticleCate.id.in_([1, 2, 3])).all()

    # 获取每个分类的已审核文章
    articles_per_page = 3
    page = int(request.args.get('page', 1))

    # 获取当前页的文章
    latest_stories = Article.query.filter(
        Article.category_id == 1,
        Article.status == 'approved'
    ).limit(articles_per_page).offset((page - 1) * articles_per_page).all()

    flower_stories = Article.query.filter(
        Article.category_id == 2,
        Article.status == 'approved'
    ).limit(articles_per_page).offset((page - 1) * articles_per_page).all()

    popular_stories = Article.query.filter(
        Article.category_id == 3,
        Article.status == 'approved'
    ).limit(10).offset((page - 1) * 10).all()

    # 获取总页数
    total_latest = Article.query.filter(Article.category_id == 1, Article.status == 'approved').count() # 获取最新故事总数
    total_flower = Article.query.filter(Article.category_id == 2, Article.status == 'approved').count() # 获取鲜花故事总数
    total_popular = Article.query.filter(Article.category_id == 3, Article.status == 'approved').count() # 获取人气故事总数

    return render_template(
        'user/story/story.html',
        user=current_user,
        latest_stories=latest_stories,
        flower_stories=flower_stories,
        popular_stories=popular_stories,
        category_names=[category.name for category in selected_categories],
        current_page=page,
        total_pages={
            'latest': (total_latest // articles_per_page) + (1 if total_latest % articles_per_page > 0 else 0),
            'flower': (total_flower // articles_per_page) + (1 if total_flower % articles_per_page > 0 else 0),
            'popular': (total_popular // 10) + (1 if total_popular % 10 > 0 else 0),
        }
    )
# 前台故事页面-分页器获取文章数据路由
@story_bp.route('/get_article_data')
def get_article_data():
    page = request.args.get('page', 1, type=int)
    category = request.args.get('category', 2, type=int)  # 默认鲜花故事
    per_page = 3

    # 获取对应分类数据[4](@ref)
    pagination = Article.query.filter(
        Article.category_id == category,
        Article.status == 'approved'
    ).paginate(page=page, per_page=per_page)

    return jsonify({
        'items': [{
            'id': item.id,
            'title': item.title,
            'published_date': item.published_date.isoformat()
        } for item in pagination.items],
        'total': pagination.total
    })


# 前台故事文章页面
@story_bp.route('/article/')
@story_bp.route('/article/<int:art_id>')
def article(art_id=None):
    user_id = session.get('user_id')
    articles = Article.query.filter(Article.id == art_id,  Article.status == 'approved').first()
    print(articles)
    if art_id is None or articles is None:
        return redirect('/story')
    if user_id:
        user = User.query.get(user_id)
        return render_template('user/story/article.html', user=user, articles=articles)
    else:
        return render_template('user/story/article.html', articles=articles)

# 前台故事上传页面
@story_bp.route('/upload_story')
@login_required
def upload_story():
    user_id = session.get('user_id')
    user = User.query.get(user_id)
    articles = Article.query.filter_by(user_id=user_id).all()
    return render_template('user/story/upload_story.html', user=user, articles=articles)


# 前台故事文章评论路由
@story_bp.route('/article/<int:art_id>/comment', methods=['POST'])
def add_article_comment(art_id):
    content = request.form.get('content')
    user_id = session.get('user_id')

    if not user_id:
        return jsonify(success=False, message='请先登录才能评论！')

    if content:
        comment = ArtComment(article_id=art_id, user_id=user_id, content=content)
        db.session.add(comment)
        db.session.commit()
        return jsonify(success=True, comment_id=comment.id, username=comment.user.username, created_at=comment.created_at.strftime('%Y-%m-%d %H:%M:%S'), content=comment.content)
    return jsonify(success=False, message='评论内容不能为空！')

# 前台故事文章删除评论路由
@story_bp.route('/article/<int:art_id>/comment/<int:comment_id>/delete', methods=['POST'])
def delete_article_comment(art_id, comment_id):
    user_id = session.get('user_id')
    comment = ArtComment.query.get(comment_id)

    if comment and comment.user_id == user_id:
        db.session.delete(comment)
        db.session.commit()
        return jsonify(success=True)
    return jsonify(success=False, message='无法删除评论！')

# 前台故事文章上传路由
@story_bp.route('/upload_article/<int:art_id>', methods=['GET', 'POST'])
@login_required
def upload_article(art_id):
    # 用户验证
    user_id = session.get('user_id')
    if not user_id:
        return jsonify({
            'success': False,
            'error': '请先登录',
            'login_url': url_for('login.login', next=request.url)
        }), 401

    user = User.query.get(user_id)
    if not user:
        return jsonify({'success': False, 'error': '用户不存在'}), 404

    # 获取或创建文章
    article = Article.query.get(art_id) if art_id != 0 else None

    if request.method == 'POST':
        # 数据校验
        title = request.form.get('title', '').strip()
        content = request.form.get('content', '')
        category_id = request.form.get('category_id', type=int)

        # 基础字段检查
        if not all([title, content, category_id]):
            return jsonify({
                'success': False,
                'error': '请填写所有必填字段',
                'fields': {
                    'title': not bool(title),
                    'content': not bool(content),
                    'category_id': not bool(category_id)
                }
            }), 400

        # 分类有效性验证
        category = ArticleCate.query.get(category_id)
        if not category:
            return jsonify({'success': False, 'error': '无效分类'}), 400

        # 内容处理
        try:
            html_content = markdown.markdown(content) # Markdown转HTML
            soup = BeautifulSoup(html_content, 'html.parser')
            clean_content = str(soup)
        except Exception as e:
            current_app.logger.error(f"内容处理失败: {str(e)}")
            return jsonify({
                'success': False,
                'error': '内容格式错误'
            }), 400

        # 数据库操作
        try:
            if art_id == 0:
                new_article = Article(
                    user_id=user.id,
                    title=title,
                    content=clean_content,
                    category_id=category_id,
                    status='pending'
                )
                db.session.add(new_article)
            else:
                if not article:
                    return jsonify({'success': False, 'error': '文章不存在'}), 404
                if article.user_id != user.id:
                    return jsonify({'success': False, 'error': '无权操作'}), 403

                article.title = title
                article.content = clean_content
                article.category_id = category_id

            db.session.commit()
            return jsonify({
                'success': True,
                'redirect_url': url_for('story.upload_story'),
                'article_id': new_article.id if art_id == 0 else article.id
            })

        except SQLAlchemyError as e:
            db.session.rollback()
            current_app.logger.error(f"数据库错误: {str(e)}")
            return jsonify({
                'success': False,
                'error': '数据保存失败'
            }), 500

    # GET请求处理
    articleCates = ArticleCate.query.all()
    return render_template(
        'user/story/upload_article.html',
        user=user,
        article=article,
        categories=articleCates
    )
# 前台上传故事页面删除文章路由
@story_bp.route('/delete_article/<int:art_id>', methods=['POST'])
@login_required
def delete_article(art_id):
    user_id = session.get('user_id')
    article = Article.query.filter_by(id=art_id, user_id=user_id).first()  # 确保是当前用户的文章

    if article:
        db.session.delete(article)
        db.session.commit()
        flash('文章已成功删除！', 'success')
    else:
        flash('文章不存在或已被删除！', 'danger')

    return redirect(url_for('story.upload_story'))  # 重定向到文章管理页面
# 注册故事管理蓝图
def register_story_bps(app):
    app.register_blueprint(story_bp, url_prefix='/story')